<template>
    <div>
      <el-upload class="upload-files" :action="url.postUploadUrl" :auto-upload="true" :on-success="onSuccess" :on-remove="onRemove" :on-error="onError"  :on-preview="handlePreview" :before-upload="beforeUpload"
        accept=".xls,.xlsx,.doc,.docx,.pdf,.jpeg,.jpg,.png,.bmp,.gif,.txt,.rar,.zip,.mp4,.avi,.flv,.mov" :file-list="fileList" style="width: 100%; min-width: 300px">
        <slot>
          <Plus size="large"/>
        </slot>  
      </el-upload>
    </div>
  </template>
  <script>
  
  
  import { ref, toRefs, reactive, onMounted, computed, watch } from 'vue';
  import { ElMessage, ElMessageBox } from "element-plus";
  import { Plus } from '@element-plus/icons-vue'
  import {DeleteById} from '@/service/index.js'
  import qs from 'qs'
  export default {
    props: {
      fileList: {// 文件列表初始化编辑使用。
        type: Array,
        default: () => {
          return [];
        }
      },
      type: ""
    },
    setup(props, ctx) {
      const baseUrl = window.REQUEST_URL;
      let state = reactive({
        url: {
          postUploadUrl: baseUrl + "/attachment/upload",
          postGetFileUrl: baseUrl + "/attachment/getFiles",
          postDelFileUrl: baseUrl + "/attachment/deletefiles",
          getDownLoadUrl: baseUrl + "/attachment/download/",
        },
      })
      const { fileList, type } = toRefs(props);
      //上传成功
      const onSuccess = (file) => {
        let tmp = file.data;
        tmp.url = state.url.getDownLoadUrl + tmp.path;
        tmp.name = tmp.filename;
        tmp.type = type.value;
        fileList.value.unshift(tmp);
        // ctx.emit("changefiles")
      }
      
      // 删除文件
      const onRemove = (file, lst) => {
        if ((file.status = "success")) {
          let fileId = file.id || file?.response?.data?.id
          fileId&&DeleteById('attachment',qs.stringify({id:fileId}))

          let idx = fileList.value.findIndex((o) => o.id == file.id);
          if (idx != -1) {
            fileList.value.splice(idx, 1);
          }
          // ctx.emit("changefiles")
        } else {
          ElMessage.warning("删除文件失败。");
        }
      }
  
      //上传失败。
      const onError = (err, file, fileList) => {
        ElMessage.warning("对不起，操作失败，请重试！");
        console.log(err);
      }
  
      // 文件上传前限制
      const beforeUpload = (file) => {
        console.log(file);
        const filename2 = file.name.substring(file.name.lastIndexOf(".") + 1);
        const filenames = [
          "xls",
          "xlsx",
          "doc",
          "docx",
          "pdf",
          "png",
          "jpeg",
          "jpg",
          "bmp",
          "gif",
          "txt",
          "rar",
          "zip",
          "mp4",
          "avi",
          "flv",
          "mov",
        ];
        const isHas = filenames.some((o) => o === filename2);
        const noSize = file.size > 10 * 1024 * 1024;
        if (!isHas) {
          ElMessage.warning("上传文件只能是pdf/word/excel/jpg/jpeg/png/bmp/gif/txt/zip/rar/mp4/avi/flv/mov格式!");
          return false;
        }
        if (noSize) {
          ElMessage.warning("上传单个文件应小于10M!");
          return false;
        }
      }
      const handlePreview =(file)=>{
        
        let filepath = file.path || file.response.data.path
        const url = window.REQUEST_URL + "/attachment/preview/" + filepath;
        let openType = "_self"
        if (filepath.toLowerCase().endsWith('pdf') ||
            filepath.toLowerCase().endsWith('png') ||
            filepath.toLowerCase().endsWith('jpg') ||
            filepath.toLowerCase().endsWith('gif') ||
            filepath.toLowerCase().endsWith('jpeg')) {
            openType = "_blank"
        }
        window.open(url, openType,'top=0,toolbar=no, menubar=no, scrollbars=no, location=no, status=no')
      }
      return {
        ...toRefs(state),
        onSuccess,
        onRemove,
        onError,
        beforeUpload,
        handlePreview
      }
    }
  };
  </script>